﻿using System;
using System.ComponentModel;

namespace Needle.Framework
{
    /// <summary>
    /// 
    /// </summary>
    public class Component : System.ComponentModel.Component, INotifyDisposed
    {
        #region contructors

        /// <summary>
        ///  
        /// </summary>
        public Component()
        { }

        /// <summary>
        /// 
        /// </summary>
        public Component(IContainer container)
        {
            container.Add(this);

        }

        #endregion

        #region  IDisposeNotification

        private bool _IsDisposed;
        /// <summary>
        /// 
        /// </summary>
        public bool IsDisposed
        {
            get { return _IsDisposed; }
        }
        /// <summary>
        /// 
        /// </summary>
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                lock (this)
                {
                    if (!_IsDisposed)
                    {
                        base.Dispose(disposing);
                        _IsDisposed = true;
                    }
                }
            }
        }

        /// <summary>
        /// Throws an ObjectDisposedException
        /// </summary>
        protected void ThrowIfDisposed()
        {
            if (_IsDisposed)
            {
                throw new ObjectDisposedException(this.ToString());
            }
        }

        #endregion

        #region services

        /// <summary>
        /// returns the requested service or null.
        /// </summary>
        protected virtual TService GetService<TService>()
            where TService : class
        {
           return this.GetService(typeof(TService)) as TService;
        }

        #endregion

        /// <summary>
        /// The component site.
        /// </summary>
        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public override ISite Site
        {
            get { return base.Site; }
            set
            {
                if (value != null) ThrowIfDisposed();
                base.Site = value;
            }
        }

    }
}
